﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Core;
using System.Data;

namespace Yuanlin.Business
{
    public class CompanyFriends : YuanlinUserControl,
        IReplyConverter<CompanyFriendCategoryReply, GetListOperation>
    {
        protected Repeater category;
        private EntityList companyFriendCategories;

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            CompanyFriendCategoryListRequest request = new CompanyFriendCategoryListRequest();
            request.UserId = UserIdFromGreenNum;
            request.PageIndex = 0;
            request.PageSize = 300;
            requestBinders.Add(RequestHelper.BuildGetCompanyFriendCategoryListRequest(this, request));
        }

        protected void category_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;

            CompanyFriendCategory companyFriendCategory = e.Item.DataItem as CompanyFriendCategory;
            if (companyFriendCategory == null)
                return;

            Repeater rptList = e.Item.FindControl("list") as Repeater;
            if (rptList == null)
                return;

            CompanyFriendListRequest request = new CompanyFriendListRequest();
            request.CategoryId=companyFriendCategory.EntityId.Value;
            request.UserId = UserIdFromGreenNum;
            request.PageIndex = 0;
            request.PageSize = 1;
            EntityList companyFriends = BusinessManager.GetCompanyFriendList(RequestHelper.BuildGetCompanyFriendListRequest(request));

            EntityList users = new EntityList();
            YuanlinUser user = null;
            foreach (CompanyFriend item in companyFriends)
            {
                user = UserManager.GetUser(item.FriendUserId.Value) as YuanlinUser;
                users.Add(user);
            }

            rptList.DataSource = users;
            rptList.DataBind();

        }

        private void BindData()
        {
            category.DataSource = companyFriendCategories;
            category.DataBind();
        }

        #region IReplyConverter<CompanyFriendCategoryReply,GetListOperation> Members

        public void ConvertReply(CompanyFriendCategoryReply reply, GetListOperation operation)
        {
            if (reply != null)
            {
                companyFriendCategories = reply.EntityList;

                if (!IsPostBack)
                {
                    category.ItemDataBound += new RepeaterItemEventHandler(category_ItemDataBound);
                    BindData();
                }
            }
        }

        #endregion
    }
}
